<?php

class Empeval_Notifications_Calculated {
	
	private $config;
	private $enabled;
	
	public function __construct() {
		$this->config = Empeval_Config::getInstance()->notifications->calculated;
		$this->enabled = (bool)$this->config->enabled;
	}
	
	public function addNotifications($userId, $bgfId) {
		if (!$this->enabled)
			return;
		$user = EmpevalUsersQuery::create()->findOneById($userId);
		if (!($user instanceof EmpevalUsers))
			throw new Empeval_Exception_App(Empeval_Exception_Codes::ERROR_USER_NOT_EXIST, array($userId));
		
		$tpl = EmpevalNotificationTemplatesQuery::create()->findOneByName(EmpevalNotificationTemplates::CALCULATED);
		if (!($tpl instanceof EmpevalNotificationTemplates))
			throw new Empeval_Exception_App(Empeval_Exception_Codes::ERROR_TPL_NOT_EXIST, array(EmpevalNotificationTemplates::FIRST_FILL_NOTIFICATION));
		$contentText = $this->addContentData($tpl->getContentText(), $bgfId);
		$contentHtml = $this->addContentData($tpl->getContentHtml(), $bgfId);
		
		$con = Propel::getConnection('vgp_empeval');
		$con->beginTransaction();
		try {
			$notification = new EmpevalNotifications();
			$notification->setStatus(EmpevalNotifications::STATUS_TO_SEND);
			$notification->setNotificationTemplates($tpl);
			$notification->save($con);
			
			$notificationData = new EmpevalNotificationData();
			$notificationData->setSubject($tpl->getSubject());
			$notificationData->setContentText($contentText);
			$notificationData->setContentHtml($contentHtml);
			$notificationData->setNotifications($notification);
			$notificationData->save($con);

			$notificationUser =new  EmpevalNotificationUsers();
			$notificationUser->setUsers($user);
			$notificationUser->setNotifications($notification);
			$notificationUser->setEmail($user->getEmail());
			$notificationUser->save($con);
			
			$con->commit();
		} catch (Exception $e) {
			$con->rollBack();
			throw $e;
		}
	}
	
	private function addContentData($content, $bgfId) {
		$content = str_replace('{$link}', Empeval_Config::getInstance()->baseUrl . sprintf($this->config->data->bonusGoalsFormUrl, $bgfId), $content);
		return $content;
	}
	
}